﻿
namespace FolderSync
{
    using System;
    using System.IO;
    public static class IOObjectsExtensions
    {
        public static bool IsReparsePoint(this DirectoryInfo d)
        {
            return d.Exists
                && (d.Attributes & FileAttributes.Directory) == FileAttributes.Directory
                && (d.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint;
        }
        public static string EnsureFolderExists(this string path, bool create = false)
        {
            var d = new DirectoryInfo(path).EnsureExists(create);
            return d == null ? null : d.FullName;
        }
        public static DirectoryInfo EnsureExists(this DirectoryInfo d, bool create = false)
        {
            if (!d.Exists)
            {
                if (create)
                {
                    EnsureExists(d.Parent, create);
                    d.Create();
                }
                else return null;
            }
            return d;
        }
        public static FileInfo LogFileinfo(this ConfigurationSet configset, bool dated = true)
        {
            if (string.IsNullOrWhiteSpace(configset.Logfile)) return null;

            var fi = new FileInfo(configset.Logfile);
            var _logfile = !dated 
                ? fi 
                : new FileInfo(string.Format("{0}\\{1}_{2}{3}",
                        fi.DirectoryName,
                        fi.Name,
                        string.Format("_{0}", DateTime.Now.ToString("yyyyMMdd_HHmmss.ff")),
                        fi.Extension
                    ));
            if (string.IsNullOrWhiteSpace(_logfile.Directory.EnsureExists(true).Name))
            {
                throw new Exception(string.Format("Unable to open log folder :«{0}»", configset.Logfile));
            }
            return _logfile;
        }
    }
}
